<template>
  <div class="app-container" v-if="!showForm">
    <!-- <div class="block"> -->
      <div class="query-wrapper" model="queryParams" style="margin-bottom: 20px;">
        <el-select v-model="queryParams.vesselName" clearable filterable placeholder="Vssel" style="width: 160px;"
          @change="selectVessel">
          <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
          </el-option>
        </el-select>
        &nbsp;&nbsp;
        <el-select v-model="queryParams.voyageNo" clearable filterable placeholder="Voyage"  style="width:100px">
          <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
          </el-option>
        </el-select>
        &nbsp;&nbsp; 
        <el-button type="primary" icon="search"  @click="search">{{ $t("ship.button.search") }}</el-button>
        <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
        <el-button type="primary" plain  v-hasPermi="['ffFixtureNote:export']" @click="applicationNo"> F/N  Application </el-button>
        <el-button type="warning" plain icon="download" v-hasPermi="['ffFixtureNote:export']" @click="exportFixtureNo">Export F/N List </el-button>
      </div> 
    <el-table stripe :border="true" :data="listData" show-overflow-tooltip style="width: 100%" @sort-change="handleSortChange" :cell-style="{textAlign:'center'}">
      <el-table-column prop="fixtureNo" label="Fixture No"  width="180" />
      <el-table-column prop="fixtureDate" label="Date" />
      <el-table-column prop="" label="Template">
        <template #default="scope">
          {{ templateTypes[scope.row.templateType] }}
        </template>
      </el-table-column>
      <el-table-column prop="clientCode" label="Client Code"   width="120" />
      <el-table-column prop="clientName" label="Client Name" show-overflow-tooltip  width="180" />
      <el-table-column prop="carrierCode" label="Carrier Code"  width="120" />
      <el-table-column prop="vesselName" label="Vessel Name" show-overflow-tooltip  width="180" />
      <el-table-column prop="voyageNo" label="Voyage"  width="100" />
      <el-table-column prop="pol" label="POL" width="120" />
      <el-table-column prop="pod" label="POD" show-overflow-tooltip />
      <el-table-column label="LAYCAN" width="180">
        <template #default="scope"> {{ scope.row.laycanStart }} --{{ scope.row.laycanEnd }} </template>
      </el-table-column>

      <el-table-column prop="status" label="Status" width="150">
        <template #default="scope">
          <!--   <el-tag v-if="scope.row.status == 2" type="warning">{{ statuss[scope.row.status] }}</el-tag>
          <el-tag v-if="scope.row.status == 1" type="success">{{ statuss[scope.row.status] }}</el-tag>
          <el-tag v-if="scope.row.status == 0">{{ statuss[scope.row.status] }}</el-tag>
        </template> -->
          <el-select v-model="scope.row.status" class="ipt" clearable
            :disabled="scope.row.status == 1 || scope.row.satus == 2 || scope.row.fixtureDate == null"
            @change="handleStatus(scope.row)">
            <el-option :key="index" :label="item" :value="index" v-for="(item, index) in statuss" />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="Operation" width="200" >
        <template #default="scope">
          <span class="btn-primary" v-hasPermi="['ffFixtureNote:edit']" @click="editClickEvent(scope.row)"> {{ $t("ship.button.edit") }}</span>
          &nbsp;&nbsp;
          <span class="btn-primary" v-hasPermi="['ffFixtureNote:remove']" @click="removeClickEvent(scope.row.fixtureId)">{{ $t("ship.button.remove") }}</span>
          &nbsp;&nbsp;
          <!-- <span class="btn-primary" @click="addClickEvent(scope.row)"> {{ $t("ship.button.draft") }}</span>
          &nbsp;&nbsp; -->
          <span class="btn-primary" v-hasPermi="['ffFixtureNote:export']" @click="exportClickEvent(scope.row)">{{ $t("ship.button.export") }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
      @pagination="pageQuery" style="float: right" />
  </div>
</template>
<script lang="ts" setup name="ffFixtureNote">
  import moment from "moment";
  import { ref, onMounted, reactive, computed, watch, getCurrentInstance } from "vue";
  import { useRouter } from "vue-router";
  import service from "@/utils/request"; 
  import { downloadFile } from "@/utils/downloadFile";
  const { proxy } = getCurrentInstance();
  const route = useRoute();
  const router = useRouter();
  import { ElNotification, ElMessageBox } from "element-plus";
  const custForm = ref(null);
  const dialogTitle = ref("");
  const total = ref(0);
  const statuss = ["UnApprove", "Approve", "Reject"];
  const templateTypes = ["Standard", "AICC"];
  const rules = ref({
    readiness: [{ required: true, message: "readiness is required", trigger: "blur" }]
  });

  let showForm = route.query?.showForm;

  let clients = reactive([]);
  let vessels = reactive([]);
  let voyages = reactive([]);

  const queryParams = reactive({
    pageNum: 1,
    pageSize: 20,
    type: 1,
    vesselName: null,
    voyageNo: null,
    fullName: null,
    orderByColumn: undefined,
    isAsc: undefined
  });

  const listData = ref([]);
  const refreshTable = async () => {
    let result = await service.get("/shipping/fixtureNote/getTable", { params: queryParams });
    listData.value = result.data;
    total.value = result.total;
  };
  const resetQuery = (data) => {
    Object.assign(queryParams, data)
    listData.value = []
  }
  const dialogFormVisible = ref(false);

  const editClickEvent = row => {
    if (row.templateType == 0) {
    localStorage.setItem("RECORD_DATA", JSON.stringify(row));
    router.push({ path: "/freightForward/fixtureNote", query: { showForm: true } });
    showForm = true;
  } else {
    localStorage.setItem("RECORD_DATA1", JSON.stringify(row));
    router.push({ path: "/contract/aiccFixtureNote" });
    showForm = true;
  }
  };


  const applicationNo = () => {
    router.push({ path: "/contract/fixtureNote/applyFixtureNo", query: { isFreight: true } });
  };

  const pageQuery = async e => {
    queryParams.pageNum = e.page;
    queryParams.pageSize = e.limit;
    refreshTable();
  };

  const search = () => {
    refreshTable();
  };

  const selectVessel = value => {
    queryParams.voyageNo = null;
    voyages = (vessels.find(item => item.vesselName == value) || { schedules: [] }).schedules;
  };

  const handleSortChange = async (column: any) => {
    queryParams.orderByColumn = column.prop;
    queryParams.isAsc = column.order; //动态取值排序顺序
    refreshTable();
  };

  const removeClickEvent = id => {
    ElMessageBox.confirm("Confirm to Remove the data？", "Confirmation Information", {
      type: "warning",
      confirmButtonText: "Confirm",
      cancelButtonText: "Cancel"
    }).then(async () => {
      await service.delete(`shipping/fixtureNote/${id}`);

      refreshTable();
      // @ts-ignore
      ElNotification.success({
        title: "Prompt information",
        message: "Delete successfully!",
        position: "bottom-right"
      });
    });
  };


  const exportClickEvent = async row => {
    downloadFile("/shipping/fixtureNote/export", row, `${moment(new Date()).format("YYYYMMDD")}_.fixtureNote.docx`);
  };

  const exportFixtureNo = async () => {
    downloadFile("/shipping/fixtureNote/exportNo", queryParams, "fixtureNote.xlsx");
  };

  const handleStatus = (row: any) => {
    if (row.status != null && row.status != 0) {
      ElMessageBox.confirm("Confirm to update the Status？", "Confirmation Information", {
        type: "warning",
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel"
      }).then(async () => {
        await service.put(`shipping/fixtureNote/updateStatus`, row);
        ElNotification.success({
          title: "Prompt information",
          message: "update Fixture Note status success!",
          position: "bottom-right"
        });
      });
    }
  };

  onMounted(async () => {
    let result = await service.get("/shipping/schedule/getAllSchedule");
    if (result) {
      vessels = result.data;
    }

    //refreshTable();
  });
</script>
<style scoped lang="scss">
  .add-container {
    padding-top: 30px;
    background-color: #fafafa;
    min-height: 100%;
  }

  .form-container {
    margin: auto;
    padding: 40px;
    width: 90%;
    background-color: #fff;
  }

  .dialog-footer {
    margin: 60px auto 0;
    width: 100%;
    text-align: center;
  }

  .el-col>span {
    margin-left: 22px;
    line-height: 32px;
    font-size: 14px;
  }

  .flex-content .el-form-item__content {
    display: inline-block;
  }

  .el-checkbox {
    color: black;
  }

  .el-checkbox__label {
    margin-top: 2px;
  }

  .clearfix::after {
    content: "";
    display: block;
    clear: both;
    visibility: hidden;
  }

  ::v-deep(.el-form-item__label) {
    font-weight: 400 !important;
  }

  .header-title {
    width: 100%;
  }

  .note-content {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
</style>